package com.sky.service.impl;

import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSONObject;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.UserMapper;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import org.apache.poi.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.IdentityHashMap;
import java.util.Map;

@Service
public class UserServiceIImpl implements UserService {
    private  static  final String JSCODE_URL ="https://api.weixin.qq.com/sns/jscode2session";
    @Autowired
    UserMapper userMapper;
    @Override
    public User login(UserLoginDTO userLoginDTO) {
         //1.调用微信官方接口 获取微信openid
        Map<String,String> paramMap=new HashMap<>();
        paramMap.put("appid","wxf3fd8aa0db1abd35");
        paramMap.put("secret","6ac8f978495797a86a7005aacaac4dc4");
        paramMap.put("js code",userLoginDTO.getCode());
        paramMap.put("grant_type","authorization_code");
        String result = HttpClientUtil.doGet(JSCODE_URL, paramMap);
        JSONObject jsonObject = JSONObject.parseObject(result);
        String openid = jsonObject.getString("openid");
        //2.判断openid是否为null，如果为null 则抛异常提示信息
        if (StringUtils.isEmpty(openid)){
            throw new LoginFailedException("微信登陆失败");
        }
        //3.先查询数据库中openid中对应的用户是否存在
        User user = userMapper.getByopenId(openid);
        //4.不存在则新用户
        if (user==null){
            user=new User();
            user.setName("微信用户");
            user.setOpenid(openid);
            user.setCreateTime(LocalDateTime.now());
            userMapper.insert(user);
        }
        //5.存在则返回用户信息
        return user;
    }
}
